<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">{{title}}</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <!--<slide-verify
        :visible.sync="dialogVisible4slideverify"
        ref="slideVerify"
        :l="10"
        :r="10"
        :w="catcha.w"
        :h="catcha.h"
        :sh="catcha.sh"
        :sw="catcha.sw"
        :blocky="catcha.blocky"
        :imgurl="catcha.imgurl"
        :miniimgurl="catcha.miniimgurl"
        :normalimgurl="catcha.normalimgurl"
        :slider-text="catcha.text"
        @verify="onVerify"
        @fail="onFail"
        @refresh="onRefresh"
      />-->
      <br/>
      <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">登录</el-button>

      <br/>
      <br/>
      <el-button :loading="loading" type="primary" style="width:100%; " @click.native.prevent="ssoClick">SSO单点登录</el-button>

      <br/>
      <br/>
      <div class="tips" style="width:100%;"/>

    </el-form>

  </div>
</template>

<script>

import {getCaptchaImg, checkCaptchaImg, selectLoginTimesByLoginName} from './api'
import SlideVerify from '@/components/SlideVerify/slideverify2'
import JSEncrypt from 'jsencrypt/bin/jsencrypt'

export default {
  name: 'Login',
  components: {SlideVerify},
  data() {
    return {
      title: '城市运行管理一网统管 - 陆家嘴金融贸易中心',
      loginForm: {
        username: '',
        password: '',
        distance: '',
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message:'用户名不能为空'/*, validator: validateUsername*/ }],
        password: [{ required: true, trigger: 'blur', message:'密码不能为空'/*, validator: validatePassword*/ }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      //
      dialogVisible4slideverify: false,
      catcha: {
        blocky: 0,
        imgurl: '',
        miniimgurl: '',
        normalimgurl: '',
        text: '向右滑动完成拼图-自动登录',
        h: 200,
        w: 450,
        sh: 62,
        sw: 62,
        modifyImg: ''
      },
      // 图片验证码传值
      slideUuid:'',
      ssoUrl: process.env.VUE_APP_SSO
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      }
    }
  },
  created() {
      this.ssoLoginByCode()
  },
  mounted() {
      this.title = process.env.VUE_APP_IndexTitle
      // 加载 slide verify code
      // this.onRefresh()
  },
  methods: {
      showPwd() {
          if (this.passwordType === 'password') {
              this.passwordType = ''
          } else {
              this.passwordType = 'password'
          }
          this.$nextTick(() => {
              this.$refs.password.focus()
          })
      },
      rsaLoginInfo(username, password, loginTimes) {
        let encrypt = new JSEncrypt();
        let publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsoYhT/we+eLgK7JBQc1M1kIGC" +
          "uGeWyXfM9pvF3y/zDeGelvy27sDdiBxfW8Z+CzNHQoNVbHqOyHaD8LBfRDIrfPBH" +
          "glpDR9dnbNPA60umP92QoTRqlkX+RjzzSRtPmSw3lygYhb4KVIWRQ0tj7Hhjj3Wy" +
          "uA35beOrlxNcYOJrQwIDAQAB";
        encrypt.setPublicKey(publicKey);
        //
        username = username.trim();
        password = password.trim();
        const userInfo = username+"_@#!#@_"+password+"_@#!#@_"+loginTimes+"_@#!#@_"+this.getCurrentDateTime();
        let rsaInfo = encrypt.encrypt(userInfo);
        return rsaInfo;
      },
      getCurrentDateTime() {
        let date = new Date();
        let y = date.getFullYear();
        let m = date.getMonth() + 1;
        m = m < 10 ? '0' + m : m;
        let d = date.getDate();
        d = d < 10 ? '0' + d : d;
        let h = date.getHours();
        h = h < 10 ? '0' + h : h;
        let min = date.getMinutes();
        min = min < 10 ? '0' + min : min;
        let s = date.getSeconds();
        s = s < 10 ? '0' + s : s;
        let ms = date.getMilliseconds();
        const time = y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s+'.'+ms;
        return time;
      },
      async handleLogin() {
        // 登录版本
        const result = await selectLoginTimesByLoginName({"loginName":this.loginForm.username})
        const loginTimes = result.obj

        // 登录
        this.$refs.loginForm.validate(valid => {
              if (valid) {
                  const loginInfoEncode = this.rsaLoginInfo(this.loginForm.username, this.loginForm.password, loginTimes)
                  this.loginForm.loginInfoEncode = loginInfoEncode;

                  this.loading = true
                  this.$store.dispatch('user/login', this.loginForm).then((r) => {
                      this.loading = false
                      this.$notify.closeAll()
                      // this.$refs.slideVerify.handleLoadBlockClear(5000)
                      if (r.success) {
                          this.$router.push({path: this.redirect || '/'})
                      }else {
                          // this.onRefresh()
                          this.notify(r);
                      }
                  }).catch(e => {
                      // this.onRefresh()
                      console.log("catch/catch")
                      console.log(e)
                      this.loading = false
                  })
              } else {
                  // this.onRefresh()
                  return false
              }
          })
      },
      ssoClick() {
        sessionStorage.setItem('point', '/dashboard')
        window.location.href = this.ssoUrl
      },
      ssoLoginByCode() {
        const code = this.getQueryVariable('code')
        console.log('跳转回来------>', code)
        if (!code) {
          return;
        }

        // 登录
        this.loading = true
        this.$store.dispatch('user/ssoLogin', code).then((r) => {
          this.loading = false
          this.$notify.closeAll()
          // this.$refs.slideVerify.handleLoadBlockClear(5000)
          if (r.success) {
            this.$router.push({path: this.redirect || '/'})
          }else {
            // this.onRefresh()
            this.notify(r);
          }
        }).catch(e => {
          // this.onRefresh()
          console.log("catch/catch")
          console.log(e)
          this.loading = false
        })

      },
      getQueryVariable(name) {
        const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
        const r = window.location.search.substr(1).match(reg)
        if (r != null) {
          return unescape(r[2])
        } else {
          return null
        }
      },
/*

      // 获取图形验证码
      getImageVerifyCode() {
        this.$refs.slideVerify.handleLoadBlock('加载中...')
        getCaptchaImg().then(result => {
          this.$refs.slideVerify.handleLoadBlockClear()
          if (result.success) {
            this.dialogVisible4slideverify = true
            let imgobj = result.map
            this.slideUuid = imgobj.slideUuid
            this.catcha.blocky = imgobj.yHeight
            this.catcha.imgurl = 'data:image/png;base64,' + imgobj.bigImage
            this.catcha.miniimgurl = 'data:image/png;base64,' + imgobj.smallImage
            this.catcha.normalimgurl = 'data:image/png;base64,' + imgobj.normalImage
            this.$nextTick(() => {
              if (this.$refs.slideVerify) {
                this.$refs.slideVerify.reset(imgobj.yHeight)
              }
            })
          }else{
            this.notify(result)
          }

        })
      },
      onVerify(distance) {
        // 验证是否成功checkKaptchaImg是后台验证接口方法
        let data = {}
        data.distance=distance
        data.slideUuid=this.slideUuid
        checkCaptchaImg(data).then(r => {
          if (r.success) {
            this.$nextTick(() => {
              if (this.$refs.slideVerify) {
                this.$refs.slideVerify.handleSuccess('自动登录...')
              }
            })
            setTimeout(() => {
              this.dialogVisible = false
              this.imgurl = ''
              this.miniimgurl = ''
              this.loginForm.distance = distance
              this.loginForm.slideUuid = this.slideUuid
              this.handleLogin()
            }, 100)
          } else {
            this.$refs.slideVerify.handleFail()
            setTimeout(() => {
              this.getImageVerifyCode()
            }, 1000)
          }
        }).catch(() => {})
      },
      // 刷新
      onRefresh() {
        this.imgurl = ''
        this.miniimgurl = ''
        this.getImageVerifyCode()
      },
      onFail() {
        console.log('fail')
      },
*/

  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 22px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
